import _ from 'lodash'
import ebus from 'libs/ebus.js'
import {mediaApi} from '../../api.js'
import * as types from '../mutation-types'

//media topo dev
export function doLoadMediaTopoDevs({dispatch, state}, {init = false} = {}) {
  if (init && state.media.topoDevs.init) {
    return
  }
  mediaApi.getItems('topoDevs').then(function(res) {
    if (res && res.data && res.data.code === 0) {
      dispatch(types.SET_MEDIA_TOPODEVS, res.data.data.topoDevs)
    }
  })
}

//monitor
export function doLoadMonitors({dispatch}) {
  dispatch(types.REFRESH_MONITORS_START)
  mediaApi.getItems('monitors').then(function(res) {
    if (res && res.data && res.data.code === 0) {
      dispatch(types.SET_MONITORS, res.data.data.monitors)
      ebus.emit('set-monitors')
    }
    dispatch(types.REFRESH_MONITORS_END)
  })
}

export function setRootMonitor({dispatch}, val) {
  dispatch(types.SET_ROOT_MONITOR, val)
}

function isFolderDevice(devType) {
  return _.includes(['nvr', 'dvr'], devType)
}

export function loadMonitorDevices({dispatch, state}, node) {
  var father = node
  let root = state.monitor.tree
  let rootMonitor = root.data
  var req = {
    topoIdOfMediaDev: rootMonitor.topoIdOfMediaDev,
    monitorName: rootMonitor.name
  }
  if (node) {
    req.deviceId = node.data.deviceId
  } else {
    father = root
  }

  mediaApi.sendCmd('getDevicesOfMonitor', req).then(function(res) {
    if (res && res.data && res.data.code === 0) {
      var devices = res.data.data.devicesOfMonitor
      let childs = _.map(devices, (item) => {
        let child = {
          name: item.name,
          childs: [],
          loading: false,
          open: false,
          isFolder: isFolderDevice(item.devType),
          data: item,
          root: root,
          father: father,
          actions: []
        }
        if (child.isFolder) {
          child.icon = 'octicon octicon-server'
        } else {
          child.icon = 'octicon octicon-device-camera-video'
        }
        return child
      })
      dispatch(types.SET_MONITOR_CHILDS, father, childs)
    }
  })
}

//record room
export function doLoadRecordRooms({dispatch, state}, {init = false} = {}) {
  if (init && state.record.room.init) {
    return
  }
  dispatch(types.REFRESH_RECORD_ROOMS_START)
  mediaApi.getItems('rooms').then(function(res) {
    if (res && res.data && res.data.code === 0) {
      dispatch(types.SET_RECORD_ROOMS, res.data.data.rooms)
    }
    dispatch(types.REFRESH_RECORD_ROOMS_END)
  })
}